import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.center_user import LoginRequiredJSONMixin


# Create your views here.






# 购物车的添加
class CartViews(LoginRequiredJSONMixin,View):
    def post(self,request):
        # 接收参数，校验参数，转换为json
        json_data = json.loads(request.body)
        sku_id = json_data.get('sku_id')
        try:
            # 获取此商品的id
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'此商品不存在'})
        # 隐藏的用户id
        user_id = request.user.id
        # 进行浏览器的客户端，选择储存的redis库·
        redis_data = get_redis_connection('carts')
        # 进行哈希增量
        redis_data.hincrby('carts_%s' % user_id,sku_id,1)
        # 进行set(集合添加)
        redis_data.sadd('selected_%s' % user_id,sku_id)
        return JsonResponse({'code':0,'errmsg':'ok'})


#购物车的展示
    def get(self, request):
        user = request.user
         # 用户已登录，查询redis购物车
        redis_conn = get_redis_connection('carts')
        # 获取redis中的购物车数据
        redis_cart = redis_conn.hgetall('carts_%s' % user.id)
        # 获取redis中的选中状态
        cart_selected = redis_conn.smembers('selected_%s' % user.id)
        """展示购物车"""
        # 获取所有商品id
        ids = redis_conn.hkeys('carts_%s' % user.id)
        cart_skus=[]
        for id in ids:
            # 根据id查询商品信息
            sku=SKU.objects.get(id=id)
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'price':sku.price,
                'count':int(redis_cart[id]),
                'selected': id in cart_selected,
                'default_image_url': sku.default_image.url,
                'amount': sku.price*int(redis_cart[id])
            })
        # new_dict  = {}
        # for key,value in redis_cart.items():
        #     new_dict[int(key)] = int(value)
        # new_list = []
        # for i in cart_selected:
        #     new_list.append(int(i))
        # skus  = SKU.objects.filter(id__in=new_dict.keys())
        # data_list = []
        # for sku in skus:
        #     # 根据id查询商品信息
        #     data_list.append({
        #         'id':sku.id,
        #         'name':sku.name,
        #         'price':sku.price,
        #         'count':new_dict.get(sku.id),
        #         'selected': sku.id in new_list,
        #         'default_image_url': sku.default_image.url,
        #         'amount': sku.price* new_dict.get(sku.id)
        #     })

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'cart_skus': cart_skus})


    # 购物车的修改
    def put(self,request):
        # 转换
        json_data = json.loads(request.body.decode())
        # 接收参数
        sku_id = json_data.get('sku_id')
        count =json_data.get('count')
        selected = json_data.get('selected',True)
        # 校验参数
        if not all((sku_id,count)):
            return JsonResponse({'code':400,'errmsg':'参数不全'})
        # 获取商品id
        try:
           sku= SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'此商品不存在'})
        # 转换count类型
        try:
            # 把count转化为int类型
            count = int(count)
        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'参数count错误'})
        user = request.user
        # 进行数据存储
        redis_data = get_redis_connection('carts')
        redis_data.hset('carts_%s' % user.id, sku_id, count)
        # 进行判断勾选状态
        if selected:
            redis_data.sadd('selected_%s' % user.id, sku_id)
        else:
            redis_data.srem('selected_%s' % user.id, sku_id)
        # 返回给前端数据
        cart_sku = {
            'id':sku_id,
            'count':count,
            'selected':selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        return JsonResponse({'code':0,'errmsg':'ok','cart_sku':cart_sku})
    # 购物车的删除
    def delete(self,request):
        json_data = json.loads(request.body.decode())
        sku_id = json_data.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'该商品不存在'})
        user=request.user
        redis_data=get_redis_connection('carts')
        redis_data.hdel('carts_%s' % user.id, sku_id)
        redis_data.srem('selected_%s' % user.id, sku_id)
        return JsonResponse({'code':0,'errmsg':'ok'})

#购物车简单实现
class CartsimpleView(LoginRequiredJSONMixin,View):
    def get(self,request):
        user = request.user
        redis_conn = get_redis_connection('carts')
        redis_cart= redis_conn.hgetall('carts_%s' % user.id)
        cart_selected = redis_conn.smembers('selected_%s' % user.id)
        cart_dict = {}
        for sku_id, count in redis_cart.items():
            cart_dict[int(sku_id)]= {
                'count': int(count),
                'selected': sku_id in cart_selected
            }
        sku_ids = redis_cart.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id':sku.id,
                'name':sku.name,
                'count':cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })
        # 响应json列表数据
        return JsonResponse({'code':0, 'errmsg':'OK', 'cart_skus':cart_skus})

# 全选功能实现
class SelectView(LoginRequiredJSONMixin,View):
    def put(self,request):
        # 1.接收参数
        json_data = json.loads(request.body)
        selected = str(json_data.get('selected'))
        print(type(selected))
        # 2.redis的数据获取
        redis_data = get_redis_connection('carts')
        # 用户id
        user_id = request.user.id
        # 建立管道
        cart = redis_data.hgetall('carts_%s' % user_id)
        # 获取所有键的数据
        id_list = cart.keys()
        pl = redis_data.pipeline()
        # 3.reids进行全选和取消全选的判断
        if selected  == 'True':
            # 全选
            # for item in id_list:
            #     redis_data.sadd('selected_%s' % user_id,int(item))
            pl.sadd('selected_%s' % user_id,*id_list)
        elif selected == 'False':
            # 取消全选
            # pl.delete('selected_%s' % user_id)
            pl.srem('selected_%s' % user_id ,*id_list)
        else:
            return JsonResponse({'code':400,'errmsg':'参数错误'})
        pl.execute()
        # 4.返回响应
        return JsonResponse({'code':0,'errmsg':'ok'})
    # def put(self,request):
    #     json_data = json.loads(request.body)
    #     selected = json_data.get('selected')
    #     redis_data =  get_redis_connection('carts')
    #     redis_cart =redis_data.hgetall('carts_%s' % request.user.id)
    #     ids = redis_cart.keys()
    #     if selected:
    #         # 方法①
    #         # for id in ids:
    #             # redis_data.sadd('selected_%s' % request.user.id,id)
    #         # 方法②拆包
    #         redis_data.sadd('selected_%s' % request.user.id,*ids)
    #     else:
    #         # 方法①
    #         # 取消全选
    #         # redis_data.delete('selected_%s' % request.user.id)
    #         # 方法②，拆包
    #         redis_data.srem('selected_%s' % request.user.id ,*ids)
    #     return JsonResponse({'code':0,'errmsg':'ok'})



